package com.mozillaonline.downloadprovider;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.mozillaonline.providers.DownloadManager;
import com.mozillaonline.providers.DownloadManager.Request;
import com.mozillaonline.providers.downloads.Constants;
import com.mozillaonline.providers.downloads.DownloadService;
import com.mozillaonline.providers.downloads.ui.DownloadList;

public class DownloadProviderActivity extends Activity implements
	OnClickListener {
    @SuppressWarnings("unused")
    private static final String TAG = DownloadProviderActivity.class.getName();

    private BroadcastReceiver mReceiver;

    EditText mUrlInputEditText;
    Button mStartDownloadButton;
    DownloadManager mDownloadManager;
    Button mShowDownloadListButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);

	mDownloadManager = new DownloadManager(getContentResolver(),
		getPackageName());
	buildComponents();
	startDownloadService();

	mReceiver = new BroadcastReceiver() {

	    @Override
	    public void onReceive(Context context, Intent intent) {
			long taskId= intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,0);
			if (taskId>0){
				try {
					//ParcelFileDescriptor fileDescriptor= mDownloadManager.openDownloadedFile(taskId);
					DownloadManager.Query myDownloadQuery = new DownloadManager.Query();
					myDownloadQuery.setFilterById(taskId);
					Cursor myDownload = mDownloadManager.query(myDownloadQuery);
					if (myDownload.moveToFirst()) {
						int fileStatus =
								myDownload.getColumnIndex(DownloadManager.COLUMN_STATUS);
						int fileUriIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);

						String fileUri = myDownload.getString(fileUriIdx);
						Long status= myDownload.getLong(fileStatus);

						Log.d(TAG,   " : status="+status);
						if (status==DownloadManager.STATUS_SUCCESSFUL){
							install(fileUri);
						}
					}
					myDownload.close();
			} catch (Exception e) {
					e.printStackTrace();
			}
			}
	    }
	};
		//DownloadManager.ACTION_NOTIFICATION_CLICKED
		IntentFilter intentFilter= new IntentFilter(
				);
		intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
	registerReceiver(mReceiver,intentFilter);
    }


	/**
	 * @title 安装应用
	 * @param uri
     */
	private void install(String uri){
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.parse(uri), Constants.INSTALL_APK);
		startActivity(intent);
	}


    @Override
    protected void onDestroy() {
	unregisterReceiver(mReceiver);
	super.onDestroy();
    }

    private void buildComponents() {
	mUrlInputEditText = (EditText) findViewById(R.id.url_input_edittext);
	mStartDownloadButton = (Button) findViewById(R.id.start_download_button);
	mShowDownloadListButton = (Button) findViewById(R.id.show_download_list_button);

	mStartDownloadButton.setOnClickListener(this);
	mShowDownloadListButton.setOnClickListener(this);

	mUrlInputEditText.setText("http://dada-client.oss-cn-hangzhou.aliyuncs.com/test/test_repair.apk");
    }

    private void startDownloadService() {
	Intent intent = new Intent();
	intent.setClass(this, DownloadService.class);
	startService(intent);
    }

    @Override
    public void onClick(View v) {
	int id = v.getId();
	switch (id) {
	case R.id.start_download_button:
	    startDownload();
	    break;
	case R.id.show_download_list_button:
	    showDownloadList();
	    break;
	default:
	    break;
	}
    }

    private void showDownloadList() {
	Intent intent = new Intent();
	intent.setClass(this, DownloadList.class);
	startActivity(intent);
    }

    private void startDownload() {
	String url = mUrlInputEditText.getText().toString();
	Uri srcUri = Uri.parse(url);
	DownloadManager.Request request = new Request(srcUri);
	request.setDestinationInExternalPublicDir(
		Environment.DIRECTORY_DOWNLOADS, "/");
	request.setDescription("货车兄弟技工版");
		//request.setVisibleInDownloadsUi(true);
		request.setShowRunningNotification(true);

	long taskId=mDownloadManager.enqueue(request);
		/*try {
			mDownloadManager.openDownloadedFile(taskId);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}*/

	}
}